/**
 * 调用微信开放域接口
 */
export default class WxOpenData {

    /**
     * 设置用户数据
     * @param {JSON} KVData json数据，数据格式为json对象，key为数据的key，value为数据的value. 示例：{key: 'score', value: "999"}
     */
    static async setUserScore(friendRankKey, KVData) {
        const userScore = await this.getUserScore(friendRankKey);
        const topScore = userScore.length > 0 ? userScore[0].value : 0;
        if (Number(KVData.value) > Number(topScore)) {
            wx.setUserCloudStorage({
                KVDataList: [KVData],
                success: (res) => {
                    console.log("setUserScore success", res)
                },
                fail: (res) => {
                    console.log(res);
                }
            });
        }
    }


    /**
    * 获取当前用户微信信息（不包含openid）
    */
    static getUserInfo(openId) {
        return new Promise((resolve, reject) => {
            wx.getUserInfo({
                openIdList: [openId],
                lang: 'zh_CN',
                success: (res) => {
                    if (res.data.length > 0) {
                        let userInfo = res.data[0];
                        userInfo.avatarUrl
                        // 使用正则表达式匹配需要的部分（从头像url解析用户id）
                        var matchResult = userInfo.avatarUrl.match(/vi_32\/(.*)\/\d+/);
                        // 提取所需的数据，它会存储在matchResult[1]中
                        userInfo.uid = matchResult ? matchResult[1] : null;
                        resolve(userInfo);
                    }
                },
                fail: (res) => {
                    reject(res);
                }
            });
        })
    }

    /**
     * 获取当前用户托管数据当中对应 key 的数据
     * @param {String} keys 要拉取的keys数据，多个用逗号分割
     */
    static getUserScore(keys) {
        return new Promise((resolve, reject) => {
            wx.getUserCloudStorage({
                keyList: [keys],
                success: (res) => {
                    // 等待数据加载
                    resolve(res.KVDataList);
                },
                fail: (res) => {
                    console.log(res);
                    reject(res);
                }
            });
        })
    }

    /**
     * 获取当前用户所有同玩好友的托管数据
     * @param {String} keys 要拉取的keys数据，多个用逗号分割
     */
    static getFriendStorage(keys) {
        return new Promise((resolve, reject) => {
            wx.getFriendCloudStorage({
                keyList: [keys],
                success: (res) => {
                    resolve(res.data);
                },
                fail: (res) => {
                    console.log(res);
                    reject(res);
                }
            });
        })
    }


    /**
     * 获取组合好的排行榜数据
     */
    static async getFriendRankList(keys, openId) {
        const userInfo = await this.getUserInfo(openId);
        const userScore = await this.getUserScore(keys);
        const friendScore = await this.getFriendStorage(keys);

        // 设置当前用户数据
        const selfItem = {
            openId: userInfo.openId,
            nickname: userInfo.nickName,
            avatarUrl: userInfo.avatarUrl,
            score: userScore[0] ? userScore[0].value : 1,
            colourClass: "",
        };

        // 设置排行榜数据
        let itemList = {
            data: [],
            selfIndex: 1,
            self: selfItem
        };

        // 从开放域获取好友数据
        itemList.data = friendScore.map(tmpData => {
            const item = {
                openId: tmpData.openid,
                nickname: tmpData.nickname,
                avatarUrl: tmpData.avatarUrl,
                score: 1,
            };

            tmpData.KVDataList.forEach(kv => {
                item[kv.key] = kv.value ? kv.value : 1;
            });

            return item;
        });

        // 降序排序
        itemList.data.sort((a, b) => b.score - a.score);

        // 设置排名效果
        itemList.data.forEach((item, index) => {
            // 设置排名前三的css效果
            if (index < 3) {
                item.colourClass = `colour${index}`;
            }

            // 设置当前用户排名
            if (item.openId === userInfo.openId) {
                itemList.selfIndex = index + 1;
            }
        });

        return itemList;
    }

    static async getAllRankList(data) {
        // 返回数据格式
        let itemList = {
            data: [],       // 列表数据
            selfIndex: 1,   // 当前用户排名
            self: {}        // 当前用户数据
        }

        // 获取排行榜数据
        const friendScore = data.playerScoreInfoList;
        itemList.data = friendScore.map(tmpData => {
            let playerInfo = tmpData.playerInfo;
            if (typeof playerInfo === 'string') {
                playerInfo = JSON.parse(tmpData.playerInfo);
            }

            return {
                openId: tmpData.playerId,
                nickname: playerInfo.nickName || "游客",
                avatarUrl: playerInfo.avatarUrl || "https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLfMjX4apaJzmvHnHZP4HCQP05XGw5YgplKteQHibricRHPqWw7lTvesibobFO9mPJETI8Bxkce6ruqQ/132",
                score: tmpData.score,
            };
        });

        // 降序排序
        itemList.data.sort((a, b) => b.score - a.score);

        // 设置排名前三的css效果
        itemList.data.forEach((item, index) => {
            if (index < 3) {
                item.colourClass = `colour${index}`;
            }
        });


        /***************** 处理当前用户数据 ******************/
        // 设置当前用户数据
        if (data.self) {
            let selfPlayerInfo = data.self.playerInfo;
            if (typeof data.self.playerInfo === 'string') {
                selfPlayerInfo = JSON.parse(data.self.playerInfo);
            }
            itemList.self = {
                openId: data.self.playerId,
                nickname: selfPlayerInfo.nickName || "游客",
                avatarUrl: selfPlayerInfo.avatarUrl || "https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLfMjX4apaJzmvHnHZP4HCQP05XGw5YgplKteQHibricRHPqWw7lTvesibobFO9mPJETI8Bxkce6ruqQ/132",
                score: data.self.score,
                colourClass: "",
            };

            // 设置当前用户排名
            itemList.selfIndex = itemList.data.findIndex(item => item.openId === data.self.playerId) + 1 || '未上榜';
        } else {
            const selfPlayerInfo = await this.getUserInfo(data.openId);
            itemList.self = {
                openId: data.openId,
                nickname: selfPlayerInfo.nickName || "游客",
                avatarUrl: selfPlayerInfo?.avatarUrl || "https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLfMjX4apaJzmvHnHZP4HCQP05XGw5YgplKteQHibricRHPqWw7lTvesibobFO9mPJETI8Bxkce6ruqQ/132",
                score: 1,
                colourClass: "",
            };

            // 设置当前用户排名
            itemList.selfIndex = itemList.data.findIndex(item => item.openId === itemList.self.openId) + 1 || '未上榜';
            itemList.self.score = itemList.data[itemList.selfIndex - 1]?.score || 1;
        }

        if (itemList.selfIndex === "未上榜") {
            itemList.colourClass = "colourMeIndex";
        }
        return itemList;
    }

}

